package com.demo.interceptor;

import com.demo.annotation.AuthPassport;
import com.demo.enums.SignTypeEnum;
import com.demo.exception.SignException;
import com.demo.properties.SignInterceptorProperties;
import com.demo.util.SignUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description 签名拦截器
 * @Author Dang Xianyue
 * @Date 2020-08-09 13:41
 * @Version 1.0
 */
@Slf4j
public class SignInterceptor implements HandlerInterceptor {

    private SignInterceptorProperties signInterceptorProperties;

    public SignInterceptor(SignInterceptorProperties signInterceptorProperties) {
        this.signInterceptorProperties = signInterceptorProperties;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(handler.getClass().isAssignableFrom(HandlerMethod.class)){
            AuthPassport authPassport = ((HandlerMethod) handler).getMethodAnnotation(AuthPassport.class);
            if(authPassport != null){
                //当有@AuthPassport注解时，按照注解中的类型进行校验
                if (authPassport.signType() == SignTypeEnum.JSON){
                    if(SignUtil.checkSignJson(request,signInterceptorProperties.getSecretKey())){
                        return true;
                    }
                    throw new SignException();
                }else if (authPassport.signType() == SignTypeEnum.FORM){
                    if(SignUtil.checkSignForm(request,signInterceptorProperties.getSecretKey())){
                        return true;
                    }
                    throw new SignException();
                }else if (authPassport.signType() == SignTypeEnum.NOT_SIGN){
                    return true;
                }
            }else {
                //当没有@AuthPassport注解时，默认按照application/x-www-form-urlencoded类型进行校验
                if(SignUtil.checkSignForm(request,signInterceptorProperties.getSecretKey())){
                    return true;
                }
                throw new SignException();
            }
        }
        return true;
    }
}
